package com.example.backend.repository;

import com.example.backend.domain.entity.TicketForward;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.Instant;
import java.util.List;

/**
 * 工单转发Repository
 */
@Repository
public interface TicketForwardRepository extends JpaRepository<TicketForward, Long> {

    /**
     * 根据工单ID查找转发记录
     */
    List<TicketForward> findByTicketIdOrderByCreatedAtDesc(Long ticketId);

    /**
     * 根据接收用户查找转发记录
     */
    Page<TicketForward> findByToUserIdOrderByCreatedAtDesc(Long toUserId, Pageable pageable);

    /**
     * 根据发送用户查找转发记录
     */
    Page<TicketForward> findByFromUserIdOrderByCreatedAtDesc(Long fromUserId, Pageable pageable);

    /**
     * 根据状态查找转发记录
     */
    List<TicketForward> findByStatusOrderByCreatedAtDesc(String status);

    /**
     * 根据转发类型查找
     */
    List<TicketForward> findByTicketIdAndForwardType(Long ticketId, String forwardType);

    /**
     * 查找待处理的转发记录
     */
    List<TicketForward> findByToUserIdAndStatusOrderByCreatedAtAsc(Long toUserId, String status);

    /**
     * 统计用户的待处理转发数量
     */
    @Query("SELECT COUNT(tf) FROM TicketForward tf WHERE tf.toUser.id = :userId AND tf.status = 'PENDING'")
    Long countPendingForwardsByUserId(@Param("userId") Long userId);

    /**
     * 查找过期的转发记录
     */
    @Query("SELECT tf FROM TicketForward tf WHERE tf.status = 'PENDING' AND tf.dueDate < :now")
    List<TicketForward> findExpiredForwards(@Param("now") Instant now);

    /**
     * 根据工单ID和状态查找
     */
    List<TicketForward> findByTicketIdAndStatus(Long ticketId, String status);
}
